﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace SoundServant.Controls
{
    /// <summary>
    /// Interaction logic for DiscControl.xaml
    /// </summary>
    public partial class DiscControl : UserControl
    {
        StoredDisc disc;
        delegate void VoidInvokeHandler();

        public DiscControl(StoredDisc d)
        {
            InitializeComponent();

            disc = d;

            Draw();

            if (disc.Current)
            {
                disc.NewTrackCreated += new StoredDisc.NewTrackCreatedEventHandler(disc_NewTrackCreated);
                disc.Finished += new StoredDisc.VoidEventHandler(disc_Finished);
                SS.TenthOfASecondTimer.Tick += new EventHandler(Timer_Tick);
            }
            foreach (StoredTrack track in disc.Tracks)
            {
                TracksHolder.Children.Add(new TrackControl(track));
            }

            disc.Updated += new StoredDisc.VoidEventHandler(disc_Updated);

        }

        void Timer_Tick(object sender, EventArgs e)
        {
            Time.Content = SS.ParseTimeSpan(disc.Length);
        }

        void disc_Finished()
        {
            SS.TenthOfASecondTimer.Tick -= Timer_Tick;
            disc.NewTrackCreated -= disc_NewTrackCreated;
            disc.Finished -= disc_Finished;

            Draw();
        }

        void disc_NewTrackCreated()
        {
            this.Dispatcher.Invoke(DispatcherPriority.Normal, (VoidInvokeHandler)delegate()
            {
                TracksHolder.Children.Add(new TrackControl(disc.CurrentTrack));
            });
        }

        void disc_Updated()
        {
            this.Dispatcher.Invoke(DispatcherPriority.Normal, (VoidInvokeHandler)delegate()
            {
            Draw();
            });
        }

        private void Draw()
        {
            
            this.Dispatcher.Invoke(DispatcherPriority.Normal, (VoidInvokeHandler)delegate()
            {
                Title.Content = disc.Title;
                Time.Content = SS.ParseTimeSpan(disc.Length);
                Number.Content = "DISC " + disc.Number;
                if (disc.Copies == 1) CopiesLabel.Content = disc.Copies + " copy of this disc has been burnt";
                else CopiesLabel.Content = disc.Copies + " copies of this disc have been burnt";
            });
        }

        private void DiscBorder_MouseDown(object sender, MouseButtonEventArgs e)
        {
            disc.Title = KeyboardEntryWindow.ShowKeyboard(disc.Title, "Disc " + disc.Number + " Title");
        }
    }
}
